package com.xywy.find;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.xywy.R;
import com.xywy.common.BaseActivity;
import com.xywy.common.constants.ResultCode;
import com.xywy.common.net.AsyncHttpClient;
import com.xywy.common.net.OnResultListenerAdapter;
import com.xywy.common.net.Parser;
import com.xywy.common.util.FileUtil;
import com.xywy.common.util.MLog;
import com.xywy.common.widget.MyProgress;
import com.xywy.common.widget.TitleBar2;
import com.xywy.find.adapter.RemindAdapter;
import com.xywy.find.bean.Remind;
import com.xywy.me.bean.UserKeeper;

/**
 * 提醒 - 列表页
 * 
 * @author xiaogd
 * 
 */
public class RemindListActivity extends BaseActivity {
	private static final String TAG = "RemindIndexActivity";
	private int fy = 1;
	private int weight = 2;
	private ListView lv;
	private RemindAdapter adapter;
	private Context mContext;
	private TextView tvGo;
	private TextView tvBack;
//	private Button btnBack;
	private List<Remind> reminds;

	
	private Handler deleteHandler = new  Handler(){
		public void handleMessage(Message msg) {
		      if(msg.what == 0x1101){
		    	  View v = (View) msg.obj;
		    	  int position = msg.arg1;
		    	  showDeleteAlert(v, position);
		      }
		};
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 设置为全屏
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.find_remind_list);
		this.preInit();
		this.initView();
		this.loadData();
		this.setListener();
	}

	@Override
	public void initView() {
		// title
		TitleBar2 titleBar = (TitleBar2) findViewById(R.id.find_remind_list_title_bar);
		TextView tvTitle = titleBar.getTitle();
		tvBack = titleBar.getTvBack();
//		btnBack = titleBar.getBtnBack();
		tvBack.setText(getString(R.string.back));
		tvGo = titleBar.getGo();
		titleBar.onClickBack(this);
		tvTitle.setText(getString(R.string.find_4));
		tvBack.setText(getString(R.string.main_tab_tv_find));
		tvGo.setText(getString(R.string.find_remind_add));

		myProgress = new MyProgress(this, 10);

		lv = (ListView) findViewById(R.id.lv_find_remind_list);
//		adapter = new RemindAdapter(this);
	}

	MyProgress myProgress;
	/**
	 * 返回
	 */
//	private Handler handler = new Handler() {
//		@Override
//		public void handleMessage(Message msg) {
//			super.handleMessage(msg);
//			MLog.i(TAG, "back:" + msg.obj + "resuletCode:" + msg.arg1);
//			myProgress.stop();
//
//			if (msg.arg1 == ResultCode.SUCCESS) {
//				reminds = getRemindList(msg.obj.toString());
////				adapter.setData(reminds);
//				adapter = new RemindAdapter(RemindListActivity.this, reminds,deleteHandler);
//				lv.setAdapter(adapter);
//			} else {
//				Toast.makeText(mContext, getString(R.string.common_fail),
//						Toast.LENGTH_LONG).show();
//			}
//		}
//	};

	// 封装Parser参数
	private Parser paramsParser;
	// 封装httpclient参数
	private HashMap<String, Object> params;
	// 异步加载
	private AsyncHttpClient asyncHttpClient;
	private SharedPreferences sp;
	private String userid;

	// 处理网络请求
	@Override
	public void loadData() {
		sp = getSharedPreferences("config", Context.MODE_PRIVATE);
//		userid = sp.getString("userid", "");
		userid = UserKeeper.getCurrentUser(this).getUserid();
		reminds = FileUtil.getList(userid+"reminds");
		if(reminds != null && reminds.size()>0){
    		for(Remind r:reminds)
    			System.out.println(r.getTime());
    	}
		adapter = new RemindAdapter(this, reminds,deleteHandler);
		lv.setAdapter(adapter);
//		myProgress.start();
//		paramsParser = new Parser();
//		// 封装参数
//		params = new HashMap<String, Object>();
//
//		// 请求路径
//		paramsParser.action = getString(R.string.find_get_remind_list);
//		// 请求方式
//		paramsParser.request = "get";
//
//		SharedPreferences sp = context.getSharedPreferences("config",
//				Context.MODE_PRIVATE);
//		String userid = sp.getString("userid", "");
//
//		// 请求参数
//		params.put("userid", userid);
//
//		paramsParser.map = params;
//		// 传递上下文
//		paramsParser.context = this.context;
//
//		asyncHttpClient = AsyncHttpClient.getInstance();
//		asyncHttpClient.exeute(paramsParser, onResultListenerAdapter);
	}

	OnResultListenerAdapter onResultListenerAdapter = new OnResultListenerAdapter() {
		@Override
		public <T extends Parser> void onSuccess(T resultParser, int resultCode) {
			super.onSuccess(resultParser, resultCode);
			Message message = Message.obtain();
			message.arg1 = resultCode;
			message.obj = resultParser.back;
//			handler.sendMessage(message);
		}
	};

	@Override
	public void preInit() {
		mContext = this.context;
		Intent intent = getIntent();
		intent.getStringExtra("remindDelete");
	}

	private void setListener() {
		tvGo.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				Intent intent = new Intent(RemindListActivity.this,
						RemindAddActivity.class);
				startActivity(intent);
				finish();
			}
		});
		tvBack.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				finish();
			}
		});
	}

	/**
	 * 进行数据解析
	 * 
	 * @param jsonStr
	 * @return
	 * 
	 */
	private List<Remind> getRemindList(String jsonStr) {
		List<Remind> list = Collections
				.synchronizedList(new ArrayList<Remind>());
		// 分别实例化，进行潜拷贝
		Remind remind = new Remind();
		try {
			JSONObject jsonObject = new JSONObject(jsonStr);
			JSONArray jsonArray = jsonObject.getJSONArray("tiplist");
			if (null != jsonArray && jsonArray.length() > 0) {
				for (int i = 0; i < jsonArray.length(); i++) {
					JSONObject json = jsonArray.getJSONObject(i);
					Remind cloneRemind = remind.clone();

					cloneRemind.setType(json.optInt("type"));
					cloneRemind.setHint(json.optString("hint"));
					cloneRemind.setDetail(json.optString("detail").replace(
							"\n", ","));
					cloneRemind.setContentid(json.optInt("contentid"));
					cloneRemind.setBelongs(json.optInt("belongs"));

					// 提醒类型（1.每周重复提醒，2.一次性提醒）
					if (json.optInt("type") == fy) {
						JSONObject timejson = json.optJSONObject("time");
						cloneRemind.setHourmin(timejson.optString("hourmin"));
						JSONArray loop = timejson.optJSONArray("looparray");
						if (null != loop && loop.length() > 0) {
							int[] loopAr = new int[loop.length()];
							for (int j = 0; j < loop.length(); j++) {
								loopAr[j] = loop.optInt(j);
							}
							cloneRemind.setLooparray(loopAr);
						}
					} else if (json.optInt("type") == weight) {
						cloneRemind.setTime(json.optLong("time"));
					}

					MLog.i(TAG, "LOOP===数组中的int值==" + cloneRemind.toString());
					list.add(cloneRemind);
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return list;
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		reminds = FileUtil.getList(userid+"reminds");
		if(reminds != null && reminds.size()>0){
    		for(Remind r:reminds)
    			System.out.println(r.getTime());
    	}
		adapter = new RemindAdapter(this, reminds,deleteHandler);
		lv.setAdapter(adapter);
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		FileUtil.clearFile(userid+"reminds");
		if(adapter != null)
			reminds = adapter.getList();
		Log.e("ondessss", reminds.size()+"");
		FileUtil.saveObjectList(userid+"reminds", reminds);
		super.onDestroy();
	}
	
	
	private void showDeleteAlert(View v, final int position) {
		final Dialog dialog = new Dialog(this, R.style.Translucent_NoTitle);
		dialog.setContentView(R.layout.wjk_delete_menu);
		TextView delete = (TextView) dialog.findViewById(R.id.delete);
		delete.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
//				weightDataDao.delete(data.get(position));
				reminds.remove(reminds.get(position));
				FileUtil.saveObjectList(userid+"reminds", reminds);
				adapter.notifyDataSetChanged();
				dialog.dismiss();
			}
		});
		Window dialogWindow = dialog.getWindow();
		WindowManager.LayoutParams lp = dialogWindow.getAttributes();
		dialogWindow.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
		dialogWindow.setGravity(Gravity.LEFT | Gravity.TOP);
		// 显示的坐标
		lp.x = v.getWidth() / 2;
		
		lp.y = v.getTop() 
				;
		dialogWindow.setAttributes(lp);
		dialog.setCanceledOnTouchOutside(true);
		dialog.show();
	}
	
	/**
	 * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
	 */
	public static int dip2px(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}
}
